import {
  getSongDetail,
  getSongLyric
} from '../../services/player'

import {
  throttle
} from "underscore"

import {
  parseLyric
} from '../../utils/parse-lyric'
import playerStore from '../../store/playerStore'
const app = getApp()
// 创建播放器
const audioContext = wx.createInnerAudioContext()
const ModeName = ['order', 'repeat', 'random', ]
Page({
  data: {
    pageTitles: ['歌曲', '歌词'],
    currentPage: 0,
    contentHeight: 300,
    id: 0,
    currentSong: {},
    lyricInfos: [],
    currentLyricText: "",
    currentLyricIndex: -1,
    currentTime: 0,
    durationTime: 0,
    sliderValue: 0,
    isSliderChangeing: false,
    isWaiting: false,
    isPlaying: true,
    lyricScrollTop: 0,

    playSongList: [],
    playSongIndex: 0,
    isFirstPlay: [],

    playModeIndex: 0, //0:顺序播放 1:单曲循环 2:随机播放
    playModeName: "order",

    height:''
  },
  onLoad(options) {
    // 获取设备信息
    this.setData({
      contentHeight: app.globalData.contentHeight
    })
    wx.getSystemInfo({
      success:(res)=>{
       this.setData({height: res.screenHeight})
      console.log(res.screenHeight);

      }
    })
    // 1.获得传入id
    const id = options.id
    // 根据id播放歌曲
    this.setupPlaySong(id)
    // 5.获取store共享数据
    playerStore.onStates(["playSongList", "playSongIndex"], this.getPlaySongInfoHandler)
  },

  updateProgress() {
    // 记录当前播放时间
    // 修改sliderValue 进度条    
    //  *100  把毫秒转换为百分制   10000 / 241584   * 100 
    const sliderValue = this.data.currentTime / this.data.durationTime * 100
    this.setData({
      currentTime: audioContext.currentTime * 1000,
      sliderValue

    })

  },


  // =============== 播放歌曲 =====================

  setupPlaySong(id) {
    this.setData({
      id,
      isPlaying: true
    })
    // 2.根据id获取歌曲详情
    getSongDetail(id).then(res => {
      this.setData({
        currentSong: res.songs[0],
        durationTime: res.songs[0].dt
      })
    
    })
    // 3.根据id获取歌词
    getSongLyric(id).then(res => {
      const lrcString = res.lrc.lyric
      const lyricInfos = parseLyric(lrcString)
      this.setData({
        lyricInfos
      })
    })

    // 播放当前歌曲
    audioContext.stop()
    audioContext.src = `https://music.163.com/song/media/outer/url?id=${id}.mp3`
    // 自动开始播放
    audioContext.autoplay = true

    // 监听播放进度
    const throttleUpdateProgress = throttle(this.updateProgress, 500, {
      leading: false,
      trailing: false
    })
    //1.更新歌曲的进度
    if (this.data.isFirstPlay) {
      this.data.isFirstPlay = false

      audioContext.onTimeUpdate(() => {
        if (!this.data.isSliderChangeing && !this.data.isWaiting) {
          throttleUpdateProgress()
        }
        // 2.匹配正确的歌词
        if (!this.data.lyricInfos.length) return
        let index = this.data.lyricInfos.length - 1
        for (let i = 0; i < this.data.lyricInfos.length; i++) {
          const info = this.data.lyricInfos[i]
          if (info.time > audioContext.currentTime * 1000) {
            index = i - 1
            break
          }
        }
        if (index === this.data.currentLyricIndex || index === -1) {
          return
        }
        const currentLyricText = this.data.lyricInfos[index].text
        this.setData({
          currentLyricText,
          currentLyricIndex: index,
          lyricScrollTop:  index * 35
        })
    
      })

      audioContext.onWaiting(() => {
        audioContext.pause()
      })
      audioContext.onCanplay(() => {
        audioContext.play()
      })
      audioContext.onEnded(() => {
        // 如果单曲循环不切下一首歌曲
        if(audioContext.loop)return
        this.changeNewSong()
      })
    }

  },


  // ===================监听事件======================

  onNavBackTap() {
    wx.navigateBack()
  },

  // 监听轮播图
  onSwpierChange(event) {
    this.setData({
      currentPage: event.detail.current
    })
  },

  onNavTabItemTap(event) {
    const index = event.target.dataset.index
    this.setData({
      currentPage: index
    })
  },


  //-------- 监听进度条--------
  onSliderChange(event) {
    this.data.isWaiting = true
    setTimeout(() => {
      this.data.isWaiting = false
    }, 1500)
    // 点击获取点击对应值
    const value = event.detail.value
    // 计算播放的位置时间   90 100   0.09  *  241584
    const currentTime = value / 100 * this.data.durationTime
    // 设置播放器计算出时间 秒钟
    audioContext.seek(currentTime / 1000)
    this.setData({
      currentTime,
      isSliderChangeing: false,
      sliderValue: value,
      isPlaying: true

    })

  },
  // 获取滑动得到的value

  onSliderChanging: throttle(function (event) {
    const value = event.detail.value
    // 根据当前值计算对应时间
    const currentTime = value / 100 * this.data.durationTime
    this.setData({
      currentTime
    })
    this.data.isSliderChangeing = true
  }, 100),


  // 播放/暂停
  onPlayOrPauseTap() {
    if (!audioContext.paused) {
      audioContext.pause()
   
    } else {
      audioContext.play()
     
    }
    this.setData({ isPlaying: audioContext.paused })

  },

    //节流 上一首/下一首
  onPrevBtnTap:throttle(function(){
    this.changeNewSong(false)
  },1000),

  onNextBtnTap:throttle(function(){
    this.changeNewSong()
  },1000),

  // 顺序/单曲/随机/
  onModeBtnTap() {
    // 1.计算新的模式
    let modeIndex = this.data.playModeIndex
    modeIndex = modeIndex + 1
    if (modeIndex === 3) {
      modeIndex = 0
    }
    // 设置是否单曲循环
    if (modeIndex === 1) {
      audioContext.loop = true
    }else{
      audioContext.loop = false
    }
    // 2.保存当前的模式
    this.setData({
      playModeIndex: modeIndex,
      playModeName: ModeName[modeIndex]
    })
  },



  changeNewSong(isNext = true) {
    // 获取之前的数据
    if(this.data.playSongList.length){
    const length = this.data.playSongList.length
    let index = this.data.playSongIndex
    // 计算最新的索引
    switch (this.data.playModeIndex) {
      case 1: //单曲循环 
      case 0: //顺序播放
        index = isNext ? index + 1 : index - 1
        if (index === length) {
          index = 0
        }
        if (index === -1) {
          index = length - 1
        }
        break
      case 2: //随机播放
        index = Math.floor(Math.random() * length)
        break
    }

    // 根据索引获取当前歌曲的信息
    const newSong = this.data.playSongList[index]
    // 保存最新索引
    playerStore.setState("playSongIndex", index)
    // 之前数据初始化
    this.setData({
      currentSong: {},
      sliderValue: 0,
      currentTime: 0,
      durationTime: 0
    })
    // 播放新歌曲
    this.setupPlaySong(newSong.id)
    }return

  },

  //============================== store共享数据==============================
  
  getPlaySongInfoHandler({
    playSongList,
    playSongIndex
  }) {
    if (playSongList) {
      this.setData({
        playSongList
      })
    }
    if (playSongIndex !== undefined) {
      this.setData({
        playSongIndex
      })
    }
  },

  onload() {
    playerStore.offStates(["playSongList", "playSongIndex"], this.getPlaySongInfoHandler)
  },
  onShareAppMessage() {
    const img = currentSong.al.picUrl
    return {
      title: 'Time Music',
      path: '/pages/main-music/main-music',
      imageUrl: img
    }
  },
})